package com.aiju.cash.ui.main.fragment;

import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.aiju.base.fragment.BaseTitleFragment;
import com.aiju.bean.Shop;
import com.aiju.cash.R;
import com.aiju.cash.core.event.BlotterEvent;
import com.aiju.cash.ui.account.AccountActivity;
import com.aiju.cash.ui.account.AccountCreatActivity;
import com.aiju.cash.ui.billing.BillingActivity;
import com.aiju.cash.ui.discount.DiscountActivity;
import com.aiju.cash.ui.good.GoodManagerActivity;
import com.aiju.cash.ui.main.MainActivity;
import com.aiju.cash.ui.main.MessageActivity;
import com.aiju.cash.ui.main.RevenueActivity;
import com.aiju.cash.ui.main.RichScanActivity;
import com.aiju.cash.ui.main.entity.ShopListEvent;
import com.aiju.cash.ui.member.MemberCardActivity;
import com.aiju.cash.ui.member.MemberManagerActivity;
import com.aiju.cash.ui.multiple_shops.activity.IShopManagerUiListener;
import com.aiju.cash.ui.multiple_shops.activity.ShopManagerActivity;
import com.aiju.cash.ui.multiple_shops.en.ShopManagerListType;
import com.aiju.cash.ui.multiple_shops.present.ipresent.IShopManagerPresent;
import com.aiju.cash.ui.multiple_shops.present.presentiml.ShopManagerPresent;
import com.aiju.cash.ui.multiple_shops.widget.MenuLinearLayout;
import com.aiju.cash.ui.pay.PayActivity;
import com.aiju.cash.ui.setting.StoreCodeActivity;
import com.aiju.cash.ui.signbank.activity.BankSignGalleryFirstActivity;
import com.aiju.cash.util.PhoneUtil;
import com.aiju.common.event.EventBusHandler;
import com.aiju.common.event.EventCenter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 佐为
 * @date: 2016-11-15 11:04
 * @version: V1.0
 * @Description: 主界面
 */
public class HomeFragment extends BaseTitleFragment implements IShopManagerUiListener {

    private GridView mGridView, mGridView2;
    // private UpMarqueeTextView mNewTextView;
    private TextView messageTextView;
    public static final int REQUESTCODE = 100;

    private IShopManagerPresent iShopManagerPresent;

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        iShopManagerPresent = new ShopManagerPresent(this, null);
        init(root);
        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
//        if ("0".equals(mUser.getRole()) && mUser.getSonShopNum() >= 1) {
//            setTitleDrawable();
//            mUser.setHavaDirectSales(true);
//        } else {
//            mUser.setHavaDirectSales(false);
//        }
//        if (!mUser.isHavaDirectSales()) {
//            setTitleNoDrawable();
//        }
    }

    @Override
    protected boolean enableDefaultBack() {
        return true;
    }

    private void init(final View root) {
        setCenterTitle(mUser.getShop().getShopName());
        ImageView rightImageView = new ImageView(getContext());
        rightImageView.setImageResource(R.mipmap.ic_home_menu);
        mAiJuTitleBarView.setCustomizedLeftView(rightImageView);
        mAiJuTitleBarView.setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity) getContext()).getSlidingMenu().toggle();
            }
        });
        setTitleTextType();
        if (mUser.getRole().equals("0") || (mUser.getShopName().equals("加盟店") && mUser.getRole().equals(1))) {//总店长和加盟店长可以显示二维码
            ImageView leftImageView = new ImageView(getContext());
            leftImageView.setImageResource(R.mipmap.icon_sys);
            mAiJuTitleBarView.setCustomizedRightView(leftImageView);
            mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), RichScanActivity.class);
                    startActivity(intent);
                }
            });
        }

        if (mUser.getRole().equals("0")) {
            iShopManagerPresent.getSwitchList(1, 10);
            mAiJuTitleBarView.getCenterTextView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getContext(), ShopManagerActivity.class);
                    Bundle b = new Bundle();
                    b.putSerializable(ShopManagerActivity.FROM, ShopManagerListType.CHANGESHOP);
                    intent.putExtras(b);
                    startActivityForResult(intent, REQUESTCODE);
                }
            });
        }

        mGridView = (GridView) root.findViewById(R.id.gv_menu);
        mGridView2 = (GridView) root.findViewById(R.id.gv_menu_2);
        messageTextView = (TextView) root.findViewById(R.id.tv_home_message);
        if (!mUser.getShop().isAlipay()) {
            root.findViewById(R.id.ly_home_message).setVisibility(View.VISIBLE);
            messageTextView.setText("您尚未签约支付宝，请联系客服");
        }
        if (!mUser.getShop().isWx()) {
            root.findViewById(R.id.ly_home_message).setVisibility(View.VISIBLE);
            messageTextView.setText("您尚未签约微信支付，请联系客服");
        }
        if (!mUser.getShop().isAlipay() && !mUser.getShop().isWx()) {
            root.findViewById(R.id.ly_home_message).setVisibility(View.VISIBLE);
            messageTextView.setText("您尚未签约任何三方支付，请联系客服");
        }

        messageTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PhoneUtil.contactUs(getActivity());
            }
        });
        root.findViewById(R.id.iv_home_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                root.findViewById(R.id.ly_home_message).setVisibility(View.GONE);
            }
        });
        if (mUser.isAdmin()) {
            root.findViewById(R.id.tv_home_account).setVisibility(View.VISIBLE);
            root.findViewById(R.id.tv_home_account).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
               /*     if (mUser.getShop().getShopAccount() != null) {
                        Intent intent = new Intent(getActivity(), AccountInfoActivity.class);
                        intent.putExtra("account", mUser.getShop().getShopAccount());
                        startActivity(intent);
                    } else {
                        startActivity(AccountActivity.class);
                    }*/
                    if (closeMenu()) {
                        return;
                    }
                    ;
                    Intent intent = new Intent(getActivity(), AccountCreatActivity.class);
                    intent.putExtra("quick", true);
                    startActivity(intent);
                }
            });
        }

        SimpleAdapter adapter = new SimpleAdapter(getActivity(),
                getItems(),
                R.layout.item_grid_menu,
                new String[]{"imageItem", "textItem"},
                new int[]{R.id.iv_menu, R.id.tv_menu_name});
        mGridView.setAdapter(adapter);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (closeMenu()) {
                    return;
                }
                TextView textView = (TextView) view.findViewById(R.id.tv_menu_name);
                if (textView.getText().equals("商品管理")) {
                    ((MainActivity) getContext()).closeMenu();
                    startActivity(GoodManagerActivity.class);
                }
                if (textView.getText().equals("消息通知")) {
                    startActivity(MessageActivity.class);
                }
                if (textView.getText().equals("我的收入")) {
                    startActivity(RevenueActivity.class);
                }
                if (textView.getText().equals("台卡")) {
                    Intent intent = new Intent(getActivity(), StoreCodeActivity.class);
                    intent.putExtra("name", mUser.getShop().getShopName());
                    intent.putExtra("type", 1);
                    startActivity(intent);
                }
                if (textView.getText().equals("账本")) {
                    startActivity(AccountActivity.class);
                }
                if (textView.getText().equals("门店管理")) {
                    Intent intent = new Intent(getContext(), ShopManagerActivity.class);
                    Bundle b = new Bundle();
                    b.putSerializable(ShopManagerActivity.FROM, ShopManagerListType.SHOPMANAGER);
                    intent.putExtras(b);
                    startActivity(intent);
                }
            }
        });

        SimpleAdapter adapter2 = new SimpleAdapter(getActivity(),
                getItems2(),
                R.layout.item_grid_menu,
                new String[]{"imageItem", "textItem"},
                new int[]{R.id.iv_menu, R.id.tv_menu_name});
        mGridView2.setAdapter(adapter2);
        mGridView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (closeMenu()) {
                    return;
                }
                TextView textView = (TextView) view.findViewById(R.id.tv_menu_name);
                if (textView.getText().equals("优惠折扣")) {
                    startActivity(DiscountActivity.class);
                }
                if (textView.getText().equals("会员卡")) {
                    startActivity(MemberCardActivity.class);
                }
                if (textView.getText().equals("会员管理")) {
                    startActivity(MemberManagerActivity.class);
                }
                if (textView.getText().equals("银行签约")) {
                    startActivity(BankSignGalleryFirstActivity.class);
                }
            }
        });

        root.findViewById(R.id.tv_home_pay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (closeMenu()) {
                    return;
                }
                ;
                startActivity(PayActivity.class);
            }
        });

        root.findViewById(R.id.tv_home_billing).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (closeMenu()) {
                    return;
                }
                ;
                startActivity(BillingActivity.class);
            }
        });

        root.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeMenu();
            }
        });
        root.findViewById(R.id.scrollView).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    closeMenu();
                }
                return false;
            }
        });

        EventCenter.bindContainerAndHandler(getLifecycle(), new EventBusHandler() {
            public void onEventMainThread(ShopListEvent event) {
                setTitleDrawable();
            }
        });

    }

    private boolean closeMenu() {
        return ((MainActivity) getContext()).closeMenu();
    }

    /**
     * 获得菜单数据
     *
     * @return
     */
    private List<Map<String, Object>> getItems() {
        List<Map<String, Object>> items = new ArrayList<>();
        if (mUser.isAdmin()) {
            Map<String, Object> item1 = new HashMap<>();
            item1.put("imageItem", R.mipmap.icon_spgl);
            item1.put("textItem", "商品管理");
            items.add(item1);
        }

        if (mUser.isAdmin()) {
            Map<String, Object> item6 = new HashMap<>();
            item6.put("imageItem", R.mipmap.icon_zb);
            item6.put("textItem", "账本");
            items.add(item6);
        }

        Map<String, Object> item3 = new HashMap<>();
        item3.put("imageItem", R.mipmap.icon_tk);
        item3.put("textItem", "台卡");
        items.add(item3);

        Map<String, Object> item4 = new HashMap<>();
        item4.put("imageItem", R.mipmap.icon_xxtz);
        item4.put("textItem", "消息通知");
        items.add(item4);

        if (mUser.isAdmin()) {
            Map<String, Object> item2 = new HashMap<>();
            item2.put("imageItem", R.mipmap.icon_wdsr);
            item2.put("textItem", "我的收入");
            items.add(item2);
        }

        if (mUser.getRole().equals("0")) {
            Map<String, Object> item7 = new HashMap<>();
            item7.put("imageItem", R.mipmap.icon_mdgl);
            item7.put("textItem", "门店管理");
            items.add(item7);
        }
        return items;
    }

    /**
     * 获得菜单数据
     *
     * @return
     */
    private List<Map<String, Object>> getItems2() {
        List<Map<String, Object>> items = new ArrayList<>();
        if (mUser.isAdmin()) {
            Map<String, Object> item6 = new HashMap<>();
            item6.put("imageItem", R.mipmap.icon_yhzk);
            item6.put("textItem", "优惠折扣");
            items.add(item6);
        }

        if (mUser.isAdmin()) {
            Map<String, Object> item5 = new HashMap<>();
            item5.put("imageItem", R.mipmap.icon_hygl);
            item5.put("textItem", "会员管理");
            items.add(item5);
        }

        if (mUser.isAdmin()) {
            Map<String, Object> item55 = new HashMap<>();
            item55.put("imageItem", R.mipmap.icon_hyk);
            item55.put("textItem", "会员卡");
            items.add(item55);
        }
        if (mUser.isAdmin()) {
            Map<String, Object> item55 = new HashMap<>();
            item55.put("imageItem", R.mipmap.icon_hyk);
            item55.put("textItem", "银行签约");
            items.add(item55);
        }
        return items;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == REQUESTCODE) {
                Shop shop = (Shop) data.getSerializableExtra("shop");
                if (shop != null) {
                    mUser.setShop(shop);
                    mUser.setStoreId(shop.getStoreId());
                    mUser.setShopId(shop.getId());
                    mAiJuTitleBarView.getCenterTextView().setText(shop.getShopName());
                    EventCenter.getInstance().post(new BlotterEvent());
                }
            }
        }
    }

    @Override
    public void NoDate() {
        mAiJuTitleBarView.getCenterTextView().setClickable(false);
        mAiJuTitleBarView.getCenterTextView().setCompoundDrawables(null, null, null, null);
    }

    @Override
    public void getShopList(List<Shop> list) {
        mUser.setSonShopNum(list.size());
        if (list.size() > 1) {
            mUser.setHavaDirectSales(true);
            setTitleDrawable();
        } else {
            mUser.setHavaDirectSales(false);
            setTitleNoDrawable();
        }
    }

    @Override
    public void exception() {
        mAiJuTitleBarView.getCenterTextView().setClickable(false);
        mAiJuTitleBarView.getCenterTextView().setCompoundDrawables(null, null, null, null);
    }

    void setTitleDrawable() {
        mAiJuTitleBarView.getCenterTextView().setFocusable(true);
        mAiJuTitleBarView.getCenterTextView().setClickable(true);
        Drawable drawable = getResources().getDrawable(R.mipmap.icon_pulldown);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        mAiJuTitleBarView.getCenterTextView().setCompoundDrawables(null, null, drawable, null);
        mAiJuTitleBarView.getCenterTextView().setCompoundDrawablePadding(MenuLinearLayout.dip2px(getContext(), 5));
    }

    void setTitleNoDrawable() {
        mAiJuTitleBarView.getCenterTextView().setClickable(false);
        mAiJuTitleBarView.getCenterTextView().setCompoundDrawables(null, null, null, null);
        mAiJuTitleBarView.getCenterTextView().setClickable(false);
    }


    void setTitleTextType(){
        AssetManager assets = getActivity().getAssets();
        Typeface fromAsset = Typeface.createFromAsset(assets, "fonts/fz.ttf");
        mAiJuTitleBarView.getCenterTextView().setTypeface(fromAsset);
    }
}
